<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" label-position="top">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="姓名" class="compact-form-item">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入姓名"
                clearable
                size="medium"
                suffix-icon="Search"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="性别" class="compact-form-item">
              <el-select
                v-model="searchForm.gender"
                placeholder="请选择"
                clearable
                size="medium"
                class="full-width-select"
              >
                <el-option label="男" value="1" />
                <el-option label="女" value="2" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
            <el-form-item label="入职日期" class="compact-form-item">
              <el-date-picker
                v-model="selectedDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                size="medium"
                class="full-width-datepicker"
                @change="handleDateRangeChange"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="24" :lg="4" :xl="4" class="search-buttons">
            <el-button type="primary" @click="loadEmployeeData" size="medium" class="search-btn">
              <el-icon><Search /></el-icon> 查询
            </el-button>
            <el-button @click="resetSearch" size="medium" class="reset-btn">
              <el-icon><Refresh /></el-icon> 重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd" class="add-btn">
        <el-icon><Plus /></el-icon> 添加员工
      </el-button>
      <el-button
        type="danger"
        @click="handleBatchDelete"
        :disabled="!selectedRows.length"
        class="batch-delete-btn"
      >
        <el-icon><Delete /></el-icon> 批量删除
      </el-button>
    </div>

    <!-- 员工表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
        :data="employeeList"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column label="性别" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.gender === 1 ? '' : 'danger'">
              {{ scope.row.gender === 1 ? '男' : '女' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column label="职位">
          <template #default="scope">
            <el-tag :type="getJobTagType(scope.row.job)">
              {{ jobMap[scope.row.job] || scope.row.job }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="salary" label="薪资" width="100" align="right">
          <template #default="scope"> ¥ {{ scope.row.salary.toLocaleString() }} </template>
        </el-table-column>
        <el-table-column label="头像" width="100" align="center">
          <template #default="scope">
            <el-avatar :size="45" :src="scope.row.image || defaultAvatar" />
          </template>
        </el-table-column>
        <el-table-column prop="entryDate" label="入职日期" width="120" />
        <el-table-column prop="deptName" label="部门" />
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <el-button
              size="small"
              @click="handleEdit(scope.row)"
              type="primary"
              class="action-btn"
            >
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row.id)"
              class="action-btn"
            >
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页组件 -->
    <el-pagination
      class="pagination"
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[5, 10, 20, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="loadEmployeeData"
      @current-change="loadEmployeeData"
      background
    />

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加员工' : '编辑员工信息'"
      v-model="dialogVisible"
      width="650px"
    >
      <el-form
        :model="employeeForm"
        label-width="100px"
        ref="employeeFormRef"
        :rules="formRules"
        label-position="left"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username" required>
              <el-input v-model="employeeForm.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="dialogType === 'add' ? '密码' : '新密码'"
              prop="password"
              :required="dialogType === 'add'"
            >
              <el-input
                v-model="employeeForm.password"
                type="password"
                show-password
                :placeholder="dialogType === 'add' ? '请输入密码' : '留空表示不修改密码'"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name" required>
              <el-input v-model="employeeForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender" required>
              <el-radio-group v-model="employeeForm.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone" required>
              <el-input v-model="employeeForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="job" required>
              <el-select v-model="employeeForm.job" placeholder="请选择职位" style="width: 100%">
                <el-option
                  v-for="item in jobOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="薪资" prop="salary" required>
              <el-input-number
                v-model="employeeForm.salary"
                :min="0"
                :step="1000"
                :precision="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职日期" prop="entryDate" required>
              <el-date-picker
                v-model="employeeForm.entryDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId" required>
              <el-select v-model="employeeForm.deptId" placeholder="请选择部门" style="width: 100%">
                <el-option
                  v-for="dept in departmentOptions"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="头像" prop="image">
              <!-- 优化后的头像上传组件 -->
              <el-upload
                action="/api/upload"
                :headers="{ token: token }"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :on-progress="handleUploadProgress"
                class="avatar-uploader"
                :disabled="!token"
                :auto-upload="true"
              >
                <div class="avatar-uploader-container">
                  <div v-if="avatarLoading" class="avatar-loading">
                    <el-icon class="loading-icon"><Loading /></el-icon>
                    <span class="progress-text">{{ uploadProgress }}%</span>
                  </div>
                  <el-avatar
                    v-else
                    :size="80"
                    :src="employeeForm.image || defaultAvatar"
                    :class="{ 'avatar-disabled': !token }"
                  />
                </div>

                <div class="avatar-uploader-tip">
                  {{ token ? '点击更换头像' : '请先登录' }}
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" class="dialog-btn">取消</el-button>
        <el-button type="primary" @click="submitForm" class="dialog-btn">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Delete, Edit, Loading } from '@element-plus/icons-vue'
import {
  queryPageApi,
  addEmpApi,
  queryInfoApi,
  updateEmpApi,
  deleteEmpApi,
  queryAllDeptApi,
} from '@/api/emp'

// 默认头像
const defaultAvatar = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')

// 职位映射
const jobMap = {
  1: '班主任',
  2: '讲师',
  3: '学工主管',
  4: '教研主管',
  5: '咨询师',
}

// 部门选项
const departmentOptions = ref([])

// 职位标签类型
const getJobTagType = (job) => {
  const types = {
    1: 'success',
    2: 'warning',
    3: '',
    4: 'info',
    5: 'danger',
  }
  return types[job] || ''
}

// 职位选项
const jobOptions = Object.entries(jobMap).map(([value, label]) => ({
  value: parseInt(value),
  label,
}))

// 响应式 token
const token = computed(() => {
  const loginUser = JSON.parse(localStorage.getItem('token') || '{}')
  return loginUser.token || ''
})

// 搜索表单
const searchForm = reactive({
  name: '',
  gender: null,
  begin: null,
  end: null,
})

// 日期范围选择器绑定值
const selectedDateRange = ref([])

// 员工列表
const employeeList = ref([])

// 加载状态
const loading = ref(false)

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
})

// 选中的行
const selectedRows = ref([])

// 对话框可见性
const dialogVisible = ref(false)

// 对话框类型（add/edit）
const dialogType = ref('add')

// 员工表单
const employeeForm = ref({
  id: null,
  username: '',
  password: '',
  name: '',
  gender: 1,
  phone: '',
  job: 1,
  salary: 0,
  image: '',
  entryDate: '',
  deptId: null,
})

// 表单验证规则
const formRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  password: [
    {
      required: dialogType.value === 'add',
      message: '请输入密码',
      trigger: 'blur',
    },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  job: [{ required: true, message: '请选择职位', trigger: 'change' }],
  salary: [{ required: true, message: '请输入薪资', trigger: 'blur' }],
  entryDate: [{ required: true, message: '请选择入职日期', trigger: 'change' }],
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
})

// 头像上传状态
const avatarLoading = ref(false)
const uploadProgress = ref(0)

// token 验证
const validateToken = () => {
  if (!token.value) {
    ElMessage.error('请先登录系统')
    return false
  }
  return true
}

// 加载所有部门数据
const loadAllDepartments = async () => {
  try {
    const response = await queryAllDeptApi()
    departmentOptions.value = response.data.map((dept) => ({
      id: dept.id,
      name: dept.name,
    }))

    // 设置默认部门ID
    if (departmentOptions.value.length > 0 && !employeeForm.value.deptId) {
      employeeForm.value.deptId = departmentOptions.value[0].id
    }
  } catch (error) {
    ElMessage.error('获取部门数据失败: ' + error.message)
  }
}

// 加载员工数据
const loadEmployeeData = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: pagination.page,
      pageSize: pagination.pageSize,
    }

    // 清除空值参数
    Object.keys(params).forEach((key) => {
      if (params[key] === null || params[key] === undefined || params[key] === '') {
        delete params[key]
      }
    })

    const response = await queryPageApi(params)

    employeeList.value = response.data.rows.map((item) => ({
      ...item,
      salary: parseFloat(item.salary) || 0,
    }))

    pagination.total = response.data.total
  } catch (error) {
    ElMessage.error('获取员工数据失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.gender = null
  searchForm.begin = null
  searchForm.end = null
  selectedDateRange.value = []
  pagination.page = 1
  loadEmployeeData()
}

// 处理选中行
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 日期范围选择器处理
const handleDateRangeChange = (dates) => {
  if (dates && dates.length === 2) {
    searchForm.begin = dates[0]
    searchForm.end = dates[1]
  } else {
    searchForm.begin = null
    searchForm.end = null
  }
}

// 添加员工
const handleAdd = () => {
  dialogType.value = 'add'
  employeeForm.value = {
    id: null,
    username: '',
    password: '',
    name: '',
    gender: 1,
    phone: '',
    job: 1,
    salary: 0,
    image: '',
    entryDate: '',
    deptId: departmentOptions.value[0]?.id || null,
  }
  dialogVisible.value = true
}

// 编辑员工
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  try {
    const response = await queryInfoApi(row.id)
    employeeForm.value = {
      ...response.data,
      password: '',
      deptId: response.data.deptId,
    }
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取员工信息失败: ' + error.message)
  }
}

// 删除员工
const handleDelete = (id) => {
  ElMessageBox.confirm('确定删除该员工吗? 此操作不可撤销', '警告', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    type: 'warning',
    confirmButtonClass: 'el-button--danger',
  })
    .then(async () => {
      try {
        await deleteEmpApi(id)
        ElMessage.success('删除成功')
        loadEmployeeData()
      } catch (error) {
        ElMessage.error('删除失败: ' + error.message)
      }
    })
    .catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) return

  ElMessageBox.confirm(
    `确定删除选中的 ${selectedRows.value.length} 位员工吗? 此操作不可撤销`,
    '批量删除警告',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger',
    },
  )
    .then(async () => {
      try {
        const ids = selectedRows.value.map((item) => item.id).join(',')
        await deleteEmpApi(ids)
        ElMessage.success('批量删除成功')
        selectedRows.value = []
        loadEmployeeData()
      } catch (error) {
        ElMessage.error('批量删除失败: ' + error.message)
      }
    })
    .catch(() => {})
}

// 上传前验证
const beforeAvatarUpload = (rawFile) => {
  // 重置进度
  uploadProgress.value = 0
  avatarLoading.value = true

  // 验证 token
  if (!validateToken()) {
    avatarLoading.value = false
    return false
  }

  // 文件类型验证
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
  if (!allowedTypes.includes(rawFile.type)) {
    ElMessage.error('只支持 JPG/PNG/GIF/WEBP 格式的图片')
    avatarLoading.value = false
    return false
  }

  // 文件大小验证
  const maxSizeMB = 10
  if (rawFile.size / 1024 / 1024 > maxSizeMB) {
    ElMessage.error(`图片大小不能超过 ${maxSizeMB}MB`)
    avatarLoading.value = false
    return false
  }

  return true
}

// 处理上传进度
const handleUploadProgress = (event) => {
  uploadProgress.value = Math.round(event.percent)
}

// 处理上传成功
const handleAvatarSuccess = (response) => {
  avatarLoading.value = false

  if (!validateToken()) return

  if (response.code === 1) {
    employeeForm.value.image = response.data
    ElMessage.success('头像上传成功')
  } else if (response.code === 401) {
    ElMessage.error('登录已过期，请重新登录')
  } else {
    ElMessage.error('头像上传失败: ' + (response.message || '未知错误'))
  }
}

// 提交表单
const submitForm = async () => {
  try {
    // 如果是编辑操作且密码为空，则删除密码字段
    const formData = { ...employeeForm.value }
    if (dialogType.value === 'edit' && !formData.password) {
      delete formData.password
    }

    if (dialogType.value === 'add') {
      await addEmpApi(formData)
      ElMessage.success('添加成功')
    } else {
      await updateEmpApi(formData)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    loadEmployeeData()
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
  }
}

// 初始化加载数据
onMounted(() => {
  loadEmployeeData()
  loadAllDepartments()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

/* 搜索区域样式 */
.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  background-color: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px 20px;
}

.search-card .el-form-item {
  margin-bottom: 0;
}

.compact-form-item {
  margin-bottom: 15px;
}

.compact-form-item :deep(.el-form-item__label) {
  padding-bottom: 5px;
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

.full-width-select {
  width: 100%;
}

.full-width-datepicker {
  width: 100%;
}

.search-buttons {
  display: flex;
  align-items: flex-end;
  padding-top: 5px;
  gap: 10px;
}

.search-btn,
.reset-btn {
  padding: 10px 20px;
  border-radius: 4px;
  font-weight: 500;
  flex: 1;
}

.search-btn {
  background-color: #409eff;
  border-color: #409eff;
}

.reset-btn {
  background-color: #f5f7fa;
  color: #606266;
}

.operation-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.add-btn,
.batch-delete-btn {
  padding: 10px 20px;
  border-radius: 4px;
  font-weight: 500;
}

.add-btn {
  background-color: #67c23a;
  border-color: #67c23a;
}

.batch-delete-btn:not(.is-disabled) {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.table-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.action-btn {
  padding: 6px 12px;
  border-radius: 4px;
  font-weight: 500;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
  padding: 15px 0;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.dialog-btn {
  padding: 10px 20px;
  border-radius: 4px;
  font-weight: 500;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table :deep(th) {
  background-color: #f5f7fa !important;
  font-weight: 600;
  color: #303133;
}

.el-tag {
  border-radius: 12px;
  padding: 0 10px;
  height: 24px;
  line-height: 22px;
}

/* 头像上传器样式 */
.avatar-uploader-container {
  position: relative;
  width: 80px;
  height: 80px;
}

.avatar-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.7);
}

.loading-icon {
  font-size: 24px;
  animation: rotating 2s linear infinite;
}

.progress-text {
  margin-left: 8px;
  font-size: 14px;
}

.avatar-disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.avatar-uploader-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  text-align: center;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-buttons {
    flex-direction: column;
    align-items: stretch;
  }

  .search-btn,
  .reset-btn {
    width: 100%;
  }
}
</style>
